#include "comm.hpp"

int main()
{
    int shmid = CreateShm();
    //log(Debug, "create shm done");

    char* shmaddr = (char*)shmat(shmid, nullptr, 0);    // 共享内存挂接进程地址空间
    //log(Debug, "attach shm done, shmaddr: 0x%x", shmaddr);
    
    // struct shmid_ds shmds;
    // shmctl(shmid, IPC_STAT, &shmds);    // IPC_STAT：将共享内存的数据拷贝到 shmds 结构体中
    // cout << "shm size: " << shmds.shm_segsz << endl;
    // cout << "shm nattch: " << shmds.shm_nattch << endl;
    // printf("shm __key: 0x%x\n", shmds.shm_perm.__key);
    // cout << "shm mode: " << shmds.shm_perm.mode << endl;

    Init init;
    int fd = open(FIFO_FILE, O_RDONLY);
    if(fd < 0) exit(3);

    while(1)
    {  
        char c;
        ssize_t s = read(fd, &c, 1);  // 写入方没有写入操作时，进程阻塞在read，通信便有了同步性
        if(s == 0) break;
        else if(s < 0) break;

        // 直接像读取自己new出来的空间内的数据一样的读取共享内存即可！
        cout << "[cilent]# " << shmaddr << endl;  
        sleep(1);  
    }

    shmdt(shmaddr);     // 去关联
    //log(Debug, "detach shm done, shmaddr: 0x%x", shmaddr);
    

    shmctl(shmid, IPC_RMID, nullptr);   // 删除共 享内存时不需要关注其属性，因此第三个参数为null
    //log(Debug, "destory shm done, shmaddr: 0x%x", shmaddr);
    return 0;
}